package com.example.demo.mq;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <pre>
 *  描述: Rabbit MQ 客户端
 * </pre>
 *
 * @author godelgnis(wujiaer)
 * @version 1.0.0
 * @date 2022/3/17 16:17
 */
@Data
@Slf4j
public class RabbitMqClient {

    private ConnectionFactory factory = new ConnectionFactory();

    private String topic;

    private static final String RABBIT_PREFIX = "rabbit://";

    private static final String TOPIC_SEPARATOR = "/";

    private static final String HOST_PORT_SEPARATOR = ":";

    public RabbitMqClient(String host, int port, String topic) {
        factory.setHost(host);
        factory.setPort(port);
        this.topic = topic;
    }

    public RabbitMqClient(String url) {
        if (StrUtil.isEmpty(url)) {
            throw new IllegalArgumentException("url is blank");
        }
        if (url.startsWith(RABBIT_PREFIX)) {
            url = url.substring(RABBIT_PREFIX.length());
        }
        int index = url.indexOf(HOST_PORT_SEPARATOR);
        String host = url.substring(0, index);
        url = url.substring(index + 1);
        index = url.indexOf(TOPIC_SEPARATOR);
        String portStr = url.substring(0, index);
        this.topic = url.substring(index + 1);
        factory.setHost(host);
        factory.setPort(Integer.parseInt(portStr));
    }


    public void publish(Object o) throws IOException, TimeoutException {
        publish(JSONUtil.toJsonStr(o));
    }

    public void publish(String content) throws IOException, TimeoutException {
        try (Connection connection = factory.newConnection()) {
            try (Channel channel = connection.createChannel()){
                channel.basicPublish(topic, topic, null, content.getBytes());
                log.info("消息推送成功");
            }
        }
    }


    public static void main(String[] args) throws IOException, TimeoutException {

        RabbitMqClient rabbitMqClient = new RabbitMqClient("192.168.54.21", 5672, "test.hello");
        rabbitMqClient.publish("hello1");
        rabbitMqClient = new RabbitMqClient("rabbit://192.168.54.21:5672/test.hello");
        rabbitMqClient.publish("hello2");

    }

}
